<?php

namespace app\admin\controller\order;

use app\common\controller\Backend;
use think\Db;
use think\Loader;

/**
 * 订单商品管理
 *
 * @icon fa fa-circle-o
 */
class Goods extends Backend
{

    /**
     * Goods模型对象
     * @var \app\admin\model\order\Goods
     */
    protected $model = null;
    protected $order_model = null;
    protected $user_model = null;
    protected $staff_model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\order\Goods;
        $this->order_model = new \app\admin\model\wanlshop\Order;
        $this->user_model = new \app\admin\model\User;
        $this->staff_model = new \app\admin\model\Staff;
        $this->view->assign("refundStatusList", $this->model->getRefundStatusList());
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("stateList", $this->model->getStateList());
    }

    protected function buildparams($searchfields = null, $relationSearch = null)
    {
        $searchfields = is_null($searchfields) ? $this->searchFields : $searchfields;
        $relationSearch = is_null($relationSearch) ? $this->relationSearch : $relationSearch;
        $search = $this->request->get("search", '');
        $filter = $this->request->get("filter", '');
        $op = $this->request->get("op", '', 'trim');
        $sort = $this->request->get("sort", !empty($this->model) && $this->model->getPk() ? $this->model->getPk() : 'id');
        $order = $this->request->get("order", "DESC");
        $offset = max(0, $this->request->get("offset/d", 0));
        $limit = max(0, $this->request->get("limit/d", 0));
        $limit = $limit ?: 999999;
        //新增自动计算页码
        $page = $limit ? intval($offset / $limit) + 1 : 1;
        if ($this->request->has("page")) {
            $page = max(0, $this->request->get("page/d", 1));
        }
        $this->request->get([config('paginate.var_page') => $page]);
        $filter = (array)json_decode($filter, true);
        $op = (array)json_decode($op, true);
        $filter = $filter ? $filter : [];
        if(isset($filter['order.state']) && in_array($filter['order.state'],['8','9','10','11','12','13'])){
            $filter['goods.state']=$filter['order.state'];
            unset($filter['order.state']);
        }
        //print_r($filter);
        //print_r($op);exit;
        $where = [];
        $alias = [];
        $bind = [];
        $name = '';
        $aliasName = '';
        if (!empty($this->model) && $relationSearch) {
            $name = $this->model->getTable();
            $alias[$name] = Loader::parseName(basename(str_replace('\\', '/', get_class($this->model))));
            $aliasName = $alias[$name] . '.';
        }
        $sortArr = explode(',', $sort);
        foreach ($sortArr as $index => & $item) {
            $item = stripos($item, ".") === false ? $aliasName . trim($item) : $item;
        }
        unset($item);
        $sort = implode(',', $sortArr);
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $where[] = [$aliasName . $this->dataLimitField, 'in', $adminIds];
        }
        if ($search) {
            $searcharr = is_array($searchfields) ? $searchfields : explode(',', $searchfields);
            foreach ($searcharr as $k => &$v) {
                $v = stripos($v, ".") === false ? $aliasName . $v : $v;
            }
            unset($v);
            $where[] = [implode("|", $searcharr), "LIKE", "%{$search}%"];
        }
        $index = 0;
        foreach ($filter as $k => $v) {
            if ($k == 'account_date' ) {
                unset($filter[$k]);
                continue;
            }
            if (!preg_match('/^[a-zA-Z0-9_\-\.]+$/', $k)) {
                continue;
            }
            $sym = $op[$k] ?? '=';
            if (stripos($k, ".") === false) {
                $k = $aliasName . $k;
            }
            $v = !is_array($v) ? trim($v) : $v;
            $sym = strtoupper($op[$k] ?? $sym);
            //null和空字符串特殊处理
            if (!is_array($v)) {
                if (in_array(strtoupper($v), ['NULL', 'NOT NULL'])) {
                    $sym = strtoupper($v);
                }
                if (in_array($v, ['""', "''"])) {
                    $v = '';
                    $sym = '=';
                }
            }

            switch ($sym) {
                case '=':
                case '<>':
                    $where[] = [$k, $sym, (string)$v];
                    break;
                case 'LIKE':
                case 'NOT LIKE':
                case 'LIKE %...%':
                case 'NOT LIKE %...%':
                    $where[] = [$k, trim(str_replace('%...%', '', $sym)), "%{$v}%"];
                    break;
                case '>':
                case '>=':
                case '<':
                case '<=':
                    $where[] = [$k, $sym, intval($v)];
                    break;
                case 'FINDIN':
                case 'FINDINSET':
                case 'FIND_IN_SET':
                    $v = is_array($v) ? $v : explode(',', str_replace(' ', ',', $v));
                    $findArr = array_values($v);
                    foreach ($findArr as $idx => $item) {
                        $bindName = "item_" . $index . "_" . $idx;
                        $bind[$bindName] = $item;
                        $where[] = "FIND_IN_SET(:{$bindName}, `" . str_replace('.', '`.`', $k) . "`)";
                    }
                    break;
                case 'IN':
                case 'IN(...)':
                case 'NOT IN':
                case 'NOT IN(...)':
                    $where[] = [$k, str_replace('(...)', '', $sym), is_array($v) ? $v : explode(',', $v)];
                    break;
                case 'BETWEEN':
                case 'NOT BETWEEN':
                    $arr = array_slice(explode(',', $v), 0, 2);
                    if (stripos($v, ',') === false || !array_filter($arr, function ($v) {
                            return $v != '' && $v !== false && $v !== null;
                        })) {
                        continue 2;
                    }
                    //当出现一边为空时改变操作符
                    if ($arr[0] === '') {
                        $sym = $sym == 'BETWEEN' ? '<=' : '>';
                        $arr = $arr[1];
                    } elseif ($arr[1] === '') {
                        $sym = $sym == 'BETWEEN' ? '>=' : '<';
                        $arr = $arr[0];
                    }
                    $where[] = [$k, $sym, $arr];
                    break;
                case 'RANGE':
                case 'NOT RANGE':
                    $v = str_replace(' - ', ',', $v);
                    $arr = array_slice(explode(',', $v), 0, 2);
                    if (stripos($v, ',') === false || !array_filter($arr)) {
                        continue 2;
                    }
                    //当出现一边为空时改变操作符
                    if ($arr[0] === '') {
                        $sym = $sym == 'RANGE' ? '<=' : '>';
                        $arr = $arr[1];
                    } elseif ($arr[1] === '') {
                        $sym = $sym == 'RANGE' ? '>=' : '<';
                        $arr = $arr[0];
                    }
                    $tableArr = explode('.', $k);
                    if (count($tableArr) > 1 && $tableArr[0] != $name && !in_array($tableArr[0], $alias)
                        && !empty($this->model) && $this->relationSearch) {
                        //修复关联模型下时间无法搜索的BUG
                        $relation = Loader::parseName($tableArr[0], 1, false);
                        $alias[$this->model->$relation()->getTable()] = $tableArr[0];
                    }
                    $where[] = [$k, str_replace('RANGE', 'BETWEEN', $sym) . ' TIME', $arr];
                    break;
                case 'NULL':
                case 'IS NULL':
                case 'NOT NULL':
                case 'IS NOT NULL':
                    $where[] = [$k, strtolower(str_replace('IS ', '', $sym))];
                    break;
                default:
                    break;
            }
            $index++;
        }
        if (!empty($this->model)) {
            $this->model->alias($alias);
        }
        $model = $this->model;
        $where = function ($query) use ($where, $alias, $bind, &$model) {
            if (!empty($model)) {
                $model->alias($alias);
                $model->bind($bind);
            }
            foreach ($where as $k => $v) {
                if (is_array($v)) {
                    call_user_func_array([$query, 'where'], $v);
                } else {
                    $query->where($v);
                }
            }
        };
        return [$where, $sort, $order, $offset, $limit, $page, $alias, $bind];
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            $_where = [];
            if ($this->request->get("user_id")) {
                $_where = ['order.user_id'=>$this->request->get("user_id")];
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            //print_r($where);
            $list = $this->order_model
                ->with('goods,shop,payway')
                ->where($where)
                ->where($_where)
                //->where('gdtype', '=', 0)
                ->order($sort, $order)
                ->paginate($limit);
            //print_r($list);exit;
            $total = $list->total();

            $rows = $list->items();

            foreach ($rows as &$val) {
                $goods = $this->model->where(['order_id'=>$val['id']])->select();
                $val['goods_name'] = join(',',array_column($goods,'title'));

                //$orderinfo = $this->order_model->where(['id'=>$val['id']])->find();
                $userinfo = $this->user_model->where(['id'=>$val['user_id']])->find();
                $val['nickname'] = !empty($userinfo)?$userinfo['nickname']:'';
                $staff_names = '';
                if ($val['staff_ids'] && !empty($val['staff_ids'])) {
                    $staff_ids = explode(',', $val['staff_ids']);
                    $staffs = $this->staff_model->where(['id'=>['in',$staff_ids]])->column('name');

                    if (count($staffs) > 0) {
                        $staff_names = implode('/', $staffs);
                    }
                }
                $val['staffs'] = $staff_names;

            }
            //echo 33333;exit;
            $result = array("total" => $total, "rows" => $rows);
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 查看
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function detail($ids = null)
    {
        $row = $this->model->get($ids);

        $row['address'] = model('app\admin\model\order\Address')
            ->where(['order_id' => $row['order_id']])
            ->order('isaddress desc')
            ->field('id,name,mobile,address,address_name')
            ->find();

        $row['pay'] = model('app\admin\model\wanlshop\Pay')
            ->where(['order_id' => $row['order_id'], 'type' => 'goods'])
            ->find();

        $row['user'] = Db::name('user')
            ->where(['id' => $row['order']['user_id']])
            ->field('id,nickname,username,mobile')
            ->find();

        $row['info'] = Db::name('wanlshop_order_goods')
            ->where(['order_id' =>  $row['order_id']])
            ->select();

        $row['refund'] = Db::name('wanlshop_order_goods g')
            ->join('wanlshop_order o', 'g.order_id = o.id', 'left')
            ->join('wanlshop_coupon c', 'o.coupon_id = c.id', 'left')
            ->where(['g.id' =>  $ids])
            ->field('if(c.price,c.price,0) as coupon_price,sum(g.freight_price+g.price) as total_price,g.freight_price,g.discount_price,o.remarks,o.state,g.state as goods_state,g.price,g.number,g.id,g.image,g.title,g.actual_payment,o.order_no,o.paymenttime')
            ->find();
        $payTime = isset($row['refund']['paymenttime']) ? date('Y-m-d H:i:s',$row['refund']['paymenttime']):"";
        $this->view->assign("payTime", $payTime);
        // 查询快递状态
        switch ($row['order']['state']) {
            case 1:
                $express = [
                    'context' => '付款后，即可将宝贝发出',
                    'status' => '提交订单',
                    'time' => date('Y-m-d H:i:s', $row['order']['createtime'])
                ];
                break;
            case 2:
                $express = [
                    'context' => '商家正在处理订单',
                    'status' => '已付款',
                    'time' => date('Y-m-d H:i:s', $row['order']['paymenttime'])
                ];
                break;
            case 3:
                $express = [
                    'status' => '已发货',
                    'context' => '包裹正在等待快递小哥揽收~',
                    'time' => date('Y-m-d H:i:s', $row['order']['delivertime'])
                ];
                break;
            case 4:
                $express = [
                    'context' => '商家正在处理订单',
                    'status' => '已收货',
                    'time' => date('Y-m-d H:i:s', $row['order']['taketime'])
                ];
                break;
            case 6:
                $express = [
                    'context' => '商家正在处理订单',
                    'status' => '已完成',
                    'time' => date('Y-m-d H:i:s', $row['order']['dealtime'])
                ];
                break;
            default:
                $express = [
                    'context' => '商家正在处理订单',
                    'status' => '已取消',
                    'time' => date('Y-m-d H:i:s', $row['order']['dealtime'])
                ];
                break;

            // default: // 获取物流
            // 	$eData = model('app\api\model\wanlshop\KuaidiSub')
            // 		->where(['express_no' => $row['express_no']])
            // 		->find();
            // 	// 获取数据 兼容PHP7.4	1.1.5升级
            // 	if(!empty($eData['data'])){
            // 		$ybData = json_decode($eData['data'], true);
            // 		// 运单状态 1.0.6升级
            // 		$statusText = ['在途','揽收','疑难','签收','退签','派件','退回','转投'];
            // 		$status = $statusText[0];
            // 		if(in_array('status', $ybData[0])){
            // 			$status = $ybData[0]['status'];
            // 		}else{
            // 			if($eData['ischeck'] === 1){
            // 				$status = $statusText[3];
            // 			}else{
            // 				$status = $statusText[$eData['state']];
            // 			}
            // 		}
            // 		$express = [
            // 			'status' => $status,
            // 			'context' => $ybData[0]['context'],
            // 			'time' => $ybData[0]['time'],
            // 		];
            // 	}else{
            // 		$express = [
            // 			'status' => '已发货',
            // 			'context' => '包裹正在等待快递小哥揽收~',
            // 			'time' => date('Y-m-d H:i:s', $row['delivertime'])
            // 		];
            // 	}
        }




        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign("kuaidi", $express);
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        // $params = $this->request->post('row/a');
        // if (empty($params)) {
        //     $this->error(__('Parameter %s can not be empty', ''));
        // }
        // $params = $this->preExcludeFields($params);
        // $result = false;
        // Db::startTrans();
        // try {
        //     //是否采用模型验证
        //     if ($this->modelValidate) {
        //         $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
        //         $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
        //         $row->validateFailException()->validate($validate);
        //     }
        //     $result = $row->allowField(true)->save($params);
        //     Db::commit();
        // } catch (ValidateException|PDOException|Exception $e) {
        //     Db::rollback();
        //     $this->error($e->getMessage());
        // }
        // if (false === $result) {
        //     $this->error(__('No rows were updated'));
        // }
        // $this->success();
    }


    /**
     * 发货
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function deliver($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');

        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            $model = new \app\admin\model\order\Order();
            $editlist = $model->where('id', $row['order_id'])->find();

            $param['express_name'] = $params['express_name'];
            $param['express_no'] = $params['express_no'];
            $param['delivertime'] = time();


            $result = $editlist->save($param);
            Db::commit();
        } catch (ValidateException | PDOException | Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 修改发货地址
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function address($ids = null)
    {
        $row = $this->model->get($ids);
        $row['address'] = model('app\admin\model\order\Address')
            ->where(['order_id' => $row['order_id']])
            ->order('isaddress desc')
            ->field('id,name,mobile,address,address_name')
            ->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');

        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            $model = new \app\admin\model\order\Address();
            $editlist = $model->where('order_id', $row['order_id'])->find();

            $param['address'] = $params['address'];
            $param['isaddress'] = 1;
            $param['updatetime'] = time();


            $result = $editlist->save($param);
            Db::commit();
        } catch (ValidateException | PDOException | Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }



}
